<!-- 必填信息 -->
<template>
  <el-form
    ref="api_POST_CompetitionVO"
    :model="api_POST_CompetitionVO"
    label-width="100px"
    size="mini"
    :rules="api_POST_CompetitionVO_Rules"
    @submit.native.prevent
  >
    <el-row :gutter="20">
      <el-col :span="12" class="form_item">
        <el-form-item label="赛事标题" prop="name">
          <el-input v-model.trim="api_POST_CompetitionVO.name" placeholder="请输入赛事标题" />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="form_item">
        <el-form-item label="认证等级" prop="levelId">
          <template v-if="!api_POST_CompetitionDTO.approveStatusCode || api_POST_CompetitionDTO.approveStatusCode === 'ApproveFailed'">
            <el-select v-model="api_POST_CompetitionVO.levelId" placeholder="请选择认证等级" style="width: 100%;">
              <el-option v-for="item in cache.competitionCertificationLevel" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </template>
          <template v-else>
            <span>
              <template v-for="item in cache.competitionCertificationLevel">
                {{ item.id === api_POST_CompetitionVO.levelId ? item.name : '' }}
              </template>
            </span>
          </template>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12" class="form_item">
        <el-form-item label="地区选择" prop="provinceCode">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.provinceCode" />
          <el-cascader v-model="areaList" :options="cache.district" :props="{ value: 'code', label: 'name' }" style="width: 100%;" @change="handleAreaChange" />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="form_item">
        <el-form-item label="比赛周期" prop="startTime">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.startTime" />
          <el-date-picker
            v-model="gameTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleGameTime"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- <el-row :gutter="20">
      <el-col :span="12" class="form_item">
        <el-form-item label="报名日期" prop="entryStartTime">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.entryStartTime" />
          <el-date-picker
            v-model="entryTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleEntryTime"
          />
        </el-form-item>
      </el-col>
    </el-row> -->
    <el-row :gutter="20">
      <el-col :span="12" class="form_item">
        <el-form-item label="联系电话" prop="contactPhoneNumber">
          <el-input v-model.trim="api_POST_CompetitionVO.contactPhoneNumber" placeholder="请输入联系人电话" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" class="form_item">
        <el-form-item label="二级域名" prop="route">
          <el-input v-model.trim="api_POST_CompetitionVO.route" placeholder="请输入">
            <template slot="prepend">{{ prefixRoute }}</template>
            <!-- <template v-if="api_POST_CompetitionDTO.tenantId || user.tenantId" slot="append">_{{ api_POST_CompetitionDTO.tenantId || user.tenantId }}</template> -->
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8" class="form_item">
        <el-tooltip class="item" effect="dark" placement="top">
          <div slot="content">文件类型：pdf, doc, docx</div>
          <el-form-item label="报名须知">
            <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.entryNotice" />
            <upload-file
              ref="entryNoticeUpload"
              :action="action"
              file-type="file"
              format-file=".pdf,.doc,.docx"
              :default-file-url="getStaticFileUrl(api_POST_CompetitionVO.entryNotice)"
              default-file-name="报名须知"
              @uploadSuccess="entryNoticeUploadSuccess"
            />
          </el-form-item>
        </el-tooltip>
      </el-col>
      <el-col :span="8" class="form_item">
        <el-tooltip class="item" effect="dark" placement="top">
          <div slot="content">文件类型：pdf, doc, docx</div>
          <el-form-item label="免责声明">
            <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.disclaimerNotice" />
            <upload-file
              ref="disclaimerNoticeUpload"
              :action="action"
              file-type="file"
              format-file=".pdf,.doc,.docx"
              :default-file-url="getStaticFileUrl(api_POST_CompetitionVO.disclaimerNotice)"
              default-file-name="免责声明"
              @uploadSuccess="disclaimerNoticeUploadSuccess"
            />
          </el-form-item>
        </el-tooltip>
      </el-col>
      <el-col :span="8" class="form_item">
        <el-tooltip class="item" effect="dark" placement="top">
          <div slot="content">文件类型：pdf, doc, docx</div>
          <el-form-item label="竞赛规程">
            <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.regulation" />
            <upload-file
              ref="regulationUpload"
              :action="action"
              file-type="file"
              format-file=".pdf,.doc,.docx"
              :default-file-url="getStaticFileUrl(api_POST_CompetitionVO.regulation)"
              default-file-name="竞赛规程"
              @uploadSuccess="regulationUploadSuccess"
            />
          </el-form-item>
        </el-tooltip>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8" class="form_item">
        <el-form-item label="选择背景" prop="backgroundImage">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.backgroundImage" />
          <photo-cropper-dialog
            ref="backgroundImagePhotoCropper"
            auto-crop-width="310px"
            auto-crop-height="166px"
            :fixed-number="[620, 332]"
            :enlarge="2"
            @photoCropperSave="backgroundImagePhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_CompetitionVO.backgroundImage }" @click="openPhotoCropper('backgroundImage')">
            <img v-if="api_POST_CompetitionVO.backgroundImage" class="show_img" :src="getStaticFileUrl(api_POST_CompetitionVO.backgroundImage)" alt="">
            <i v-else class="el-icon-plus" />
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="form_item">
        <el-form-item label="上传logo" prop="logoImage">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.logoImage" />
          <photo-cropper-dialog
            ref="logoImagePhotoCropper"
            auto-crop-width="400px"
            auto-crop-height="400px"
            :fixed-number="[400, 400]"
            :enlarge="1"
            @photoCropperSave="logoImagePhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_CompetitionVO.logoImage }" @click="openPhotoCropper('logoImage')">
            <img v-if="api_POST_CompetitionVO.logoImage" class="show_img" :src="getStaticFileUrl(api_POST_CompetitionVO.logoImage)" alt="">
            <i v-else class="el-icon-plus" />
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="form_item">
        <el-form-item label="上传封面图" prop="coverImage">
          <el-input v-show="false" v-model.trim="api_POST_CompetitionVO.coverImage" />
          <photo-cropper-dialog
            ref="coverImagePhotoCropper"
            auto-crop-width="316px"
            auto-crop-height="208px"
            :fixed-number="[316, 208]"
            :enlarge="1"
            @photoCropperSave="coverImagePhotoCropperSave"
          />
          <div :class="{ upload_game_img: true, border: !api_POST_CompetitionVO.coverImage }" @click="openPhotoCropper('coverImage')">
            <img v-if="api_POST_CompetitionVO.coverImage" class="show_img" :src="getStaticFileUrl(api_POST_CompetitionVO.coverImage)" alt="">
            <i v-else class="el-icon-plus" />
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { Api_POST_CompetitionVO } from '@/lib/form/events';
import { Api_POST_CompetitionVO_Rules } from '@/lib/validate/events';
import { api_POST_EventsManagementCompetition, api_PUT_EventsManagementCompetitionId, api_GET_EventsManagementCompetitionId } from '@/extend/api/gameswaggerApi/app';
import { CopyData, deepCopy } from '@/lib';
import uploadFile from '@/components/UploadFile';
import photoCropperDialog from './photoCropperDialog';
export default {
  name: 'RequiredInfo',
  components: {
    uploadFile,
    photoCropperDialog
  },
  data() {
    return {
      action: `${WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE}/api/upload/document`,
      // 二级域名路由前缀
      prefixRoute: '',
      api_POST_CompetitionVO: new Api_POST_CompetitionVO(),
      api_POST_CompetitionVO_old: new Api_POST_CompetitionVO(),
      api_POST_CompetitionVO_Rules: new Api_POST_CompetitionVO_Rules(),
      api_POST_CompetitionDTO: {},
      // 地区
      areaList: [],
      // 报名日期
      entryTime: [],
      // 比赛日期
      gameTime: []
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      user: state => state.user
    })
  },
  created() {
    // this.initRules();
    this.getDictByType(['district', 'competitionCertificationLevel']);
    this.getDict();
    this.prefixRoute = `${location.origin}/league.html#/home/`;
    this.gameId = this.$route.params.parentId || '';
    // 编辑
    if (this.gameId) {
      this.getGameInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    init() {
      this.$refs.api_POST_CompetitionVO.resetFields();
      this.areaList = [];
      this.entryTime = [];
      this.gameTime = [];
      this.$refs.entryNoticeUpload.init();
      this.$refs.disclaimerNoticeUpload.init();
      this.$refs.regulationUpload.init();
      this.$refs.backgroundImagePhotoCropper.init();
      this.$refs.logoImagePhotoCropper.init();
      this.$refs.coverImagePhotoCropper.init();
    },
    // 初始化验证信息
    initRules() {
      const _this = this;
      this.api_POST_CompetitionVO_Rules.startTime.push({
        validator(rule, value, callback) {
          console.log(_this.gameTime);
          // 比赛开始日期不能小于报名开始日期
          const _startTime = _this.gameTime && _this.gameTime[0];
          const _endTime = _this.gameTime && _this.gameTime[1];
          if (_this.gameTime.length > 1 && new Date(_startTime) < new Date(_this.api_POST_CompetitionVO.entryStartTime)) {
            callback(new Error('比赛开始日期不能小于报名开始日期'));
          }
          // 比赛结束日期不能小于报名结束日期
          if (_this.gameTime.length > 1 && new Date(_endTime) < new Date(_this.api_POST_CompetitionVO.entryEndTime)) {
            callback(new Error('比赛结束日期不能小于报名结束日期'));
          }
          callback();
        },
        trigger: 'change'
      });
    },
    // 获取赛事详情
    getGameInfo() {
      api_GET_EventsManagementCompetitionId(this.gameId).then(res => {
        this.api_POST_CompetitionDTO = res || {};
        CopyData(this.api_POST_CompetitionDTO, this.api_POST_CompetitionVO);
        this.areaList = [this.api_POST_CompetitionVO.provinceCode, this.api_POST_CompetitionVO.cityCode, this.api_POST_CompetitionVO.countyCode];
        // this.entryTime = [this.api_POST_CompetitionVO.entryStartTime, this.api_POST_CompetitionVO.entryEndTime];
        this.gameTime = [this.api_POST_CompetitionVO.startTime, this.api_POST_CompetitionVO.endTime];
        // entryStartTime 和 entryEndTime  在联赛中没有意义，但不能为空，所以这样处理
        this.entryTime = this.gameTime;
        this.api_POST_CompetitionVO_old = deepCopy(this.api_POST_CompetitionVO);
      }, () => {
        this.$message({ type: 'error', message: '获取赛事详情失败！' });
      });
    },
    validSameData() {
      return new Promise(resolve => {
        if (JSON.stringify(this.api_POST_CompetitionVO_old) === JSON.stringify(this.api_POST_CompetitionVO)) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    },
    submit() {
      return new Promise((resolve, reject) => {
        console.log(this.api_POST_CompetitionVO);
        // 联赛isFinal是false
        this.api_POST_CompetitionVO.isFinal = false;
        this.$refs.api_POST_CompetitionVO.validate(valid => {
          if (valid) {
            // 编辑
            if (this.gameId) {
              this.editGame().then(res => {
                this.api_POST_CompetitionVO_old = deepCopy(this.api_POST_CompetitionVO);
                resolve(res);
              }, error => {
                reject(error);
              });
            } else {
              this.newGame().then(res => {
                this.api_POST_CompetitionVO_old = deepCopy(this.api_POST_CompetitionVO);
                resolve(res);
              }, error => {
                reject(error);
              });
            }
          } else {
            reject(false);
          }
        });
      });
    },
    // 新建赛事
    newGame() {
      return new Promise((resolve, reject) => {
        // 设置默认值
        this.api_POST_CompetitionVO.typeCode = 'League';
        // 地址不能为空，所以随便填了
        this.api_POST_CompetitionVO.address = 'address';
        this.api_POST_CompetitionVO.statusCode = this.api_POST_CompetitionVO.statusCode || 'Scheduled';
        this.api_POST_CompetitionVO.approveStatusCode = this.api_POST_CompetitionVO.approveStatusCode || 'NotApproved';
        api_POST_EventsManagementCompetition(this.api_POST_CompetitionVO).then(res => {
          this.$message({ type: 'success', message: '新增赛事成功！' });
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '新增赛事失败！' + error.error.message });
        });
      });
    },
    // 编辑赛事
    editGame() {
      return new Promise((resolve, reject) => {
        api_PUT_EventsManagementCompetitionId(this.gameId, this.api_POST_CompetitionVO).then(res => {
          this.$message({ type: 'success', message: '编辑赛事成功！' });
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '编辑赛事失败！' + error.error.message });
        });
      });
    },
    // 处理地区显示
    handleAreaChange() {
      this.api_POST_CompetitionVO.provinceCode = this.areaList && this.areaList[0];
      this.api_POST_CompetitionVO.cityCode = this.areaList && this.areaList[1];
      this.api_POST_CompetitionVO.countyCode = this.areaList && this.areaList[2];
    },
    // 处理报名时间
    // handleEntryTime() {
    //   this.api_POST_CompetitionVO.entryStartTime = this.entryTime && this.entryTime[0];
    //   this.api_POST_CompetitionVO.entryEndTime = this.entryTime && this.entryTime[1];
    // },
    // 处理比赛时间
    handleGameTime() {
      this.api_POST_CompetitionVO.startTime = this.gameTime && this.gameTime[0];
      this.api_POST_CompetitionVO.endTime = this.gameTime && this.gameTime[1];
      // entryStartTime 和 entryEndTime  在联赛中没有意义，但不能为空，所以这样处理
      this.api_POST_CompetitionVO.entryStartTime = this.gameTime && this.gameTime[0];
      this.api_POST_CompetitionVO.entryEndTime = this.gameTime && this.gameTime[1];
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    openPhotoCropper(code) {
      this.$refs[code + 'PhotoCropper'].open(this.api_POST_CompetitionVO[code]);
    },
    // 报名须知上传
    entryNoticeUploadSuccess(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'entryNotice', fileUrl.tempUrl);
    },
    // 免责声明上传
    disclaimerNoticeUploadSuccess(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'disclaimerNotice', fileUrl.tempUrl);
    },
    // 竞赛规程上传
    regulationUploadSuccess(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'regulation', fileUrl.tempUrl);
    },
    // 背景回显
    backgroundImagePhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'backgroundImage', fileUrl.tempUrl);
    },
    // logo回显
    logoImagePhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'logoImage', fileUrl.tempUrl);
    },
    // 封面图回显
    coverImagePhotoCropperSave(fileUrl) {
      this.$set(this.api_POST_CompetitionVO, 'coverImage', fileUrl.tempUrl);
    }
  }
};
</script>
<style scoped>
.upload_game_img {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  font-size: 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}
.upload_game_img.border {
  border: 1px dotted #DCDFE6;
}
.upload_game_img:hover {
  border-color: #409eff;
}
.upload_game_img .show_img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  vertical-align: top;
}
</style>
